#include "Scheduler.h"
#include "IThread.h"

/*
Extremely simplistic round-robin scheduler.
Holds an array of IThread's, and calls 'run' for whatever the current thread is.
Current thread is set by calls to 'nextThread', which just increments the currentThread value modulo numThreads.
nextThread is intended to be called by a timer interrupt.
This way, no matter what the code is doing, the scheduler will switch threads asynchronously at a defined interval
*/

Scheduler::Scheduler(){
    _numThreads = 0;
    _currentThread = -1;
}

void Scheduler::addThread(IThread* thread) volatile{
    if(_numThreads < 5){
        _threads[_numThreads] = thread;
        _numThreads++;
    }
    else
        Serial.write("addThread(): Thread limit exceeded\n");
}

void Scheduler::nextThread() volatile{
    if(_numThreads > 0)
        _currentThread = (_currentThread + 1) % _numThreads;
    else
        _currentThread = -1;
}

void Scheduler::runCurrentThread() volatile{
    if(_currentThread != -1)
        _threads[_currentThread]->run();
}
